//
//  LeaderInspMergeController.m
//  Estate
//
//  Created by heyong on 16/9/6.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "LeaderInspMergeController.h"
#import "DoubleLabCell.h"
#import "DefaineCell.h"
#import "addDiaryHeadView.h"
#import "B_wuLiaoCell.h"
#import "LeaderYijianCell.h"
#import "explainTableViewCell.h"
#import "LeaderAddInspController.h"
#import "LeaderAuditController.h"

@interface LeaderInspMergeController (){
    FMDatabase *_db;
    NSString *_totalTime;
    NSString *_inspectState;
    //是否是全部合格
    BOOL allQualified;
    //巡检项巡检状态
    NSString *inspectState;
    //任务巡检状态
    NSString *_taskState;
}

@property (copy, nonatomic) NSString *totalDes;
@end


@implementation LeaderInspMergeController
- (NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray=[NSMutableArray array];
    }
    return _dataArray;
}

- (TPKeyboardAvoidingTableView *)tableView{
    if(_tableView==nil){
        _tableView=[[TPKeyboardAvoidingTableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT) ];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.bounces=NO;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator=NO;
        [_tableView registerNib:[UINib nibWithNibName:@"DoubleLabCell" bundle:nil] forCellReuseIdentifier:@"dCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"JLRJTitleCell" bundle:nil] forCellReuseIdentifier:@"titleCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"DefaineCell" bundle:nil] forCellReuseIdentifier:@"textCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"B_wuLiaoCell" bundle:nil] forCellReuseIdentifier:@"sCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"LeaderYijianCell" bundle:nil] forCellReuseIdentifier:@"detailss"];
        [_tableView registerNib:[UINib nibWithNibName:@"explainTableViewCell" bundle:nil] forCellReuseIdentifier:@"explainCell"];
    }
    return _tableView;
}

- (void)viewDidAppear:(BOOL)animated{
    //刷新页面
    NSNotification *notice1=[NSNotification notificationWithName:@"Refresh_xjrw" object:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice1];
    
    NSNotification * notice = [NSNotification notificationWithName:@"Refresh_xjzz" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"巡检合并任务ID：%@",self.processId);
    [self.view addSubview:self.tableView];
    self.view.backgroundColor=[UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
    _db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    if(self.isEdit){
        //添加右上方提交按钮
        self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"wancheng"] style:UIBarButtonItemStyleDone target:self action:@selector(clickSave)];
    }else{
        [self initData];
    }
    self.title=@"一键汇总";

    //默认全部合格
    allQualified=YES;
    
//    //查询该任务当前状态
//   NSString *sta=[LSUtility quertInspectStateByProcessId:self.processId];
//    if([sta isEqualToString:@"2"]){
//        _taskState=@"带汇总";
//    }else if ([sta isEqualToString:@"3"]){
//        _taskState=@"待审阅";
//    }else if ([sta isEqualToString:@"4"]){
//        _taskState=@"待整改";
//    }else if ([sta isEqualToString:@"5"]){
//        _taskState=@"已完成";
//    }
    
    _taskState=@"";
    
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(initData) name:@"Refresh_xjhbym" object:nil];
    
}

#pragma mark-查询一键汇总
- (void)initData{
    //检查任务是否完全结束
    [LSUtility processRecordStateExistEnd:self.processId];
    
    [self.dataArray removeAllObjects];
    
    NSString *sql=[NSString stringWithFormat:@"select * from  INSPECT_TOTAL_RECORD where INSPECT_PROCESS_ID='%@'",self.processId];
    [_db open];
    FMResultSet *result=[_db executeQuery:sql];
    NSString *itemArrStr=@"";
    while ([result next]) {
        _totalId=[result stringForColumn:@"ID"];
        //创建时间
        _totalTime=[result stringForColumn:@"CREATE_TIME"];
        //说明
        _totalDes=[result stringForColumn:@"INSPECT_TOTAL_DESC"];
        //详情数组
        itemArrStr=[result stringForColumn:@"INSPECT_TOTAL_INFO"];
    }
    
    [_db close];
    //数据转化为数组
    NSArray *arr=[LSUtility dictionaryWithJsonString:itemArrStr];
    NSMutableArray * dataArr=[NSMutableArray array];
    //添加分类标题到各个数据中
    for(int i=0;i<arr.count;i++){
        NSMutableDictionary *dic=arr[i];
        NSString *item=dic[@"inspectItemId"];
        if(![item isEqualToString:@""]){
            //根据子类查询父级巡检项
            NSMutableDictionary *parentDic=[LSUtility getParentNameByitemId:item];
          
            //parentDic  count为0 代表直接是父级
            if(parentDic.count==0){
                //直接查询自己的标题
                NSMutableDictionary *parentDic1=[LSUtility getParentNameByitemIdss:item];
                NSString *name=parentDic1[@"name"];
                [dic setObject:name forKey:@"info"];
            //子级
            }else{
                NSString *name=parentDic[@"name"];
                [dic setObject:name forKey:@"info"];
            }
            [dic setObject:@"" forKey:@"types"];
            //得到记录人姓名
            NSString *recordName=[LSUtility getuserIdByUserName:dic[@"inspectUserId"]][@"REAL_NAME"];
            [dic setObject:DEFISNUL(recordName) forKey:@"name"];
            
        }else{
            [dic setObject:@"其它" forKey:@"info"];
            [dic setObject:@"extra" forKey:@"types"];
            NSString *recordName=[LSUtility getuserIdByUserName:dic[@"inspectUserId"]][@"REAL_NAME"];
            [dic setObject:DEFISNUL(recordName) forKey:@"name"];
        }
        [dataArr addObject:dic];
    }
    
    //根据分类标题拆分成数组
    // 遍历,创建组数组,组数组中的每一个元素是一个模型数组
    NSMutableArray *_groupArr = [NSMutableArray arrayWithCapacity:0];
    NSMutableArray *currentArr = [NSMutableArray array];
    if(dataArr.count>0){
        // 因为肯定有一个字典返回,先添加一个
        [currentArr addObject:dataArr[0]];
        [_groupArr addObject:currentArr];
        // 如果不止一个,才要动态添加
        if(dataArr.count > 1){
            for (int i=0; i<dataArr.count; i++) {
                
                NSMutableDictionary *dic_1=dataArr[i];
                NSString *type=dic_1[@"info"];
                
                // 先取出组数组中  上一个模型数组的第一个字典模型的groupID
                NSMutableArray *preModelArr = [_groupArr objectAtIndex:_groupArr.count-1];
                NSString* type_2 = [[preModelArr objectAtIndex:0] objectForKey:@"info"] ;
                
                // 取出当前字典,根据type比较,如果相同则添加到同一个模型数组;如果不相同,说明不是同一个组的
                if ([type isEqualToString:type_2]) {
                    [currentArr addObject:dic_1];
                }else{
                    // 如果不相同,说明 有新的一组,那么创建一个模型数组,并添加到组数组_groupArr
                    currentArr = [NSMutableArray array];
                    [currentArr addObject:dic_1];
                    [_groupArr addObject:currentArr];
                }
            }
        }
        
        for (int i=0; i<_groupArr.count; i++) {
            NSMutableArray *array=_groupArr[i];
            if(i==0){
                if(array.count>1){
                    //移除第一次添加对比的数据
                    [array removeObjectAtIndex:0];
                }
            }
            //得到标题
            NSDictionary *dic=[array firstObject];
            NSDictionary *tempDic=@{@"title":dic[@"info"],@"array":array};
            [self.dataArray addObject:tempDic];
        }
    }
    
    [self.tableView reloadData];

}

#pragma mark- 一键保存数据
- (void)clickSave{
    [self firstTotalRecord:self.flag];
}

-(void)firstTotalRecord:(NSString *)type{
    
    DBHelper *helper=[DBHelper help];
    
    //先删除状态为3 或者5的
    [_db open];
    //修改流程记录为DEL
//    NSString *sql_1= [NSString stringWithFormat:@"update INSPECT_PROCESS_RECORD SET LOCAL_MODIFY_STATE='DEL' where INSPECT_PROCESS_ID='%@' and INSPECT_ITEM_STATE in('3','5')",self.processId];
    NSString *sql_1= [NSString stringWithFormat:@"delete from  INSPECT_PROCESS_RECORD where INSPECT_PROCESS_ID='%@' and INSPECT_RESULT!='2' and INSPECT_ITEM_STATE in('3','5')",self.processId];

    if([_db executeUpdate:sql_1]){
        NSLog(@"状态3\5删除成功");
    };
    [_db close];
    
    /*
     *  一键汇总 数据结构化
     */
//    NSLog(@"一键汇总数据:%@",self.dataArray);
    NSMutableArray *totalInfoArr=[NSMutableArray array];
    for (NSDictionary *dic_1 in self.dataArray) {
        NSArray *arr=dic_1[@"array"];
        for (NSDictionary *dic_2 in arr) {
            NSString *recordId=dic_2[@"ids"];
            NSString *userItemId=dic_2[@"userItemId"];
            NSString *inspectUserId=dic_2[@"inspectUserId"];
            NSString *inspectItemId=dic_2[@"inspectItemId"];
            NSString *inspectItemInfo=dic_2[@"inspectItemInfo"];
            NSString *inspectResult=dic_2[@"state"];
            NSDictionary *dic=@{@"recordId":recordId,@"userItemId":userItemId,@"inspectUserId":inspectUserId,@"inspectItemId":inspectItemId,@"inspectItemInfo":inspectItemInfo,@"inspectResult":inspectResult};
            [totalInfoArr addObject:dic];
         
            //不合格新增待整改  合格新增已完成
            NSString *userItemState=@"";
            if([inspectResult isEqualToString:@"0"]){
                userItemState=@"3";
                if(![LSUtility updateIsDown:userItemId table:INSPECT_USER_ITEM]){
                    //修改用户巡检项表
                    [LSUtility updateInspectUserItembyIdADD:userItemId andState:3];
                }else{
                    //修改用户巡检项表
                    [LSUtility updateInspectUserItembyId:userItemId andState:3];
                }
               
            }else if ([inspectResult isEqualToString:@"1"]){
                userItemState=@"5";
                if(![LSUtility updateIsDown:userItemId table:INSPECT_USER_ITEM]){
                    //修改用户巡检项表
                    [LSUtility updateInspectUserItembyIdADD:userItemId andState:5];
                }else{
                    [LSUtility updateInspectUserItembyId:userItemId andState:5];
                }
            }
            
            
            /*
             *  巡检流程记录新增
             */
            NSDictionary *oldDic=@{
                                   @"ID":[NSUUID UUID].UUIDString,
                                   @"INSPECT_ITEM_STATE":userItemState,
                                   @"CREATE_TIME":[LSUtility nowTime],
                                   @"CREATE_IP":[LSUtility getIPAddress],
                                   @"LOCAL_MODIFY_STATE":@"ADD",
                                   };
            
            NSString *state2Id=[LSUtility queryInspectStateId:recordId state:@"2"];
//            NSLog(@"状态为2的id:%@",state2Id);
            NSMutableDictionary *dicc=[LSUtility queryInspectRecordById:state2Id];
            //字典新增其它字典
            [dicc setValuesForKeysWithDictionary:oldDic];
//            NSLog(@"插入%@",dicc);
            //流程记录表新增状态为3 待整改 或者已完成
            [helper DataBase:_db insertKeyValues:dicc intoTable:INSPECT_PROCESS_RECORD];
        }
    }
    
    //转化为json串
    NSString *totalInfo=[LSUtility dictionaryToJson_2:totalInfoArr];

    //第一次一键汇总本地新增
    if([self.flag isEqualToString:@""]){
        //一键汇总表插入
        NSDictionary *dic_1=@{
                            @"ID":[NSUUID UUID].UUIDString,
                            @"INSPECT_PROCESS_ID":self.processId,
                            @"INSPECT_TOTAL_TIME":[LSUtility TimeNow],
                            @"INSPECT_TOTAL_INFO":totalInfo,
                            @"INSPECT_TOTAL_DESC":DEFISNUL(_totalDes),
                            @"INSPECT_TOTAL_USER":USERID,
                            @"EXTEND_INFO":@"",
                            @"CREATE_TIME":[LSUtility nowTime],
                            @"CREATE_IP":[LSUtility getIPAddress],
                            @"CREATE_USER_NAME":USERID,
                            @"LOCAL_MODIFY_STATE":@"ADD",
                            @"LOCAL_MODIFY_USER_NAME":@"",
                            @"LOCAL_MODIFY_TIME":@""
                            };
        BOOL isOk_01=[helper DataBase:_db insertKeyValues:dic_1 intoTable:INSPECT_TOTAL_RECORD];
        if(isOk_01){
            NSLog(@"一键汇总成功,新增成功");
        }
    }else{
        //一键汇总表修改
        NSDictionary *dics=@{
                             @"INSPECT_TOTAL_INFO":totalInfo,
                             @"INSPECT_TOTAL_DESC":DEFISNUL(_totalDes),
                             @"MODIFY_TIME":[LSUtility nowTime],
                             @"MODIFY_IP":[LSUtility getIPAddress],
                             @"LOCAL_MODIFY_STATE":@"ADD",
                             };
        [helper DataBase:_db updateTable:INSPECT_TOTAL_RECORD setKeyValues:dics whereCondition:@{@"ID":_totalId}];
        NSLog(@"一键汇总成功,修改成功 id:%@",_totalId);
    }
    
    //全部合格
    NSString *procesState=@"3";
    if(allQualified){
        procesState=@"5";
    }
    NSDictionary *dics=@{
                         @"INSPECT_STATE":procesState,
                         @"MODIFY_TIME":[LSUtility nowTime],
                         @"MODIFY_IP":[LSUtility getIPAddress],
                         @"LOCAL_MODIFY_STATE":@"MOD"
                         };
    NSLog(@"修改前任务id:%@",self.processId);
    //修改任务状态
    [helper DataBase:_db updateTable:INSPECT_PROCESS setKeyValues:dics whereCondition:@{@"ID":self.processId}];
    //检查任务是否完全结束
    [LSUtility processRecordStateExistEnd:self.processId];

    //刷新页面
    NSNotification *notice=[NSNotification notificationWithName:@"Refresh_xjrw" object:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice];
    NSNotification * notice2 = [NSNotification notificationWithName:@"Refresh_xjzz" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice2];
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count+2;
}
//返回组
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //得到类别下content
    if(section==0)//第一组
    {
        return 4;
    }else if(section==self.dataArray.count+1)//倒数第一组
    {
        return 1;
    }
    else//查询动态添加组
    {
        NSDictionary *dict=self.dataArray[section-1];
        NSMutableArray *arr=[dict objectForKey:@"array"];
        return arr.count;
    }
    
}
//组尾
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    //第一组
    if(section==0||section==self.dataArray.count+1){
        UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH-20, 15)];
        view.backgroundColor=[UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
        //波浪线
        UIImageView *img=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 8)];
        img.backgroundColor=[UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
        img.image=[UIImage imageNamed:@"juchishang"];
        [view addSubview:img];
        return view;
        
    }else{
        //横线
        UIView *line=[[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 1)];
        line.backgroundColor=[UIColor colorWithRed:0.89 green:0.89 blue:0.90 alpha:1.00];
        return line;
    }
}
//组尾高
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if(section==0){
        return 15;
    }else
        return 1;
}

//组头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    //第一组 最后一组
    if(section==0 ||section==self.dataArray.count+1)
    {
        return nil;
        
    } else if(section==1)
    {
        addDiaryHeadView *headView=[[addDiaryHeadView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 30)];
        NSString *title=self.dataArray[section-1][@"title"];
        
        if(self.isEdit){
            NSRange range=[title rangeOfString:@"("];
            if (range.location != NSNotFound) {
                title=[title substringToIndex:range.location];
            }
        }
        
        headView.title.font=[UIFont systemFontOfSize:16.*BIZ];
        headView.title.text=title;
        return headView;
    }
    else
    {
        UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 25)];
        UILabel *titleLab=[[UILabel alloc]initWithFrame:CGRectMake(8, 8, DEF_SCREEN_WIDTH, 15)];
        titleLab.font=[UIFont systemFontOfSize:15.];
        view.backgroundColor=[UIColor whiteColor];
        titleLab.textColor=[UIColor colorWithRed:0.47 green:0.48 blue:0.49 alpha:1.00];
     
        NSString *title=self.dataArray[section-1][@"title"];
        if(self.isEdit){
            NSRange range=[title rangeOfString:@"("];
            if (range.location != NSNotFound) {
                title=[title substringToIndex:range.location];
            }
        }
        titleLab.font=[UIFont systemFontOfSize:16.*BIZ];
        titleLab.text=title;
        [view addSubview:titleLab];
        return view;
    }
}

//组头高
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if(section==0||section==self.dataArray.count+1){
        return 0.1;
    }else if (section==1){
        return 30.;
    }else
        return 25;
}


- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  //  WEAKSELF
    //第一组
    if(indexPath.section==0){
        if(indexPath.row==0){
            DoubleLabCell  *cell=[tableView dequeueReusableCellWithIdentifier:@"dCell" forIndexPath:indexPath];
            
            cell.backgroundColor=[UIColor colorWithRed:0.85 green:0.93 blue:0.97 alpha:1.00];
            //标题
            NSDictionary *titDic=[LSUtility quertInspectProcessName:self.processId];
            NSString *title=[NSString stringWithFormat:@">> %@  %@",[titDic objectForKey:@"time"],[titDic objectForKey:@"title"]];
            if(self.isEdit){
                [cell setTitle:title AndTitleColor:[UIColor colorWithRed:0.24 green:0.64 blue:0.61 alpha:1.00] AndDetail:_taskState AndDetailColor:[UIColor colorWithRed:0.88 green:0.35 blue:0.42 alpha:1.00]];
            }else{
                [cell setTitle:title AndTitleColor:[UIColor colorWithRed:0.24 green:0.64 blue:0.61 alpha:1.00] AndDetail:_taskState AndDetailColor:[UIColor colorWithRed:0.88 green:0.35 blue:0.42 alpha:1.00]];
            }
            
            return cell;
            
        }else{
            if(indexPath.row==1){
                DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                //根据id 查询项目名
                NSString *proname=[LSUtility  getProjectNameByProjectId:PROID][@"PROJECT_NAME"];
                [cell setTitle:@"项    目:" andDetail:proname andLeftConstraint:8];
                
                return cell;
            }else if (indexPath.row==2){
                DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                NSString *userName=[LSUtility  getuserIdByUserName:USERID][@"REAL_NAME"];
                [cell setTitle:@"记 录 人:" andDetail:userName andLeftConstraint:8];
                
                return cell;
            }else {
                DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                if(self.isEdit){
                    [cell setTitle:@"时    间:" andDetail:[LSUtility nowTime] andLeftConstraint:8];
                }else{
                    [cell setTitle:@"时    间:" andDetail:_totalTime andLeftConstraint:8];
                }
                
                return cell;
            }
            
        }
    } else if(indexPath.section==self.dataArray.count+1)//最后一组
    {
        explainTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"explainCell" forIndexPath:indexPath];
        cell.isEdit = self.isEdit;
        cell.textValueChangedBlock=^(NSString *value){
            _totalDes=value;
        };
        dispatch_async(dispatch_get_main_queue(), ^{
            [cell setTitle:@"说   明:" andPlaceHolder:@"请输入说明" andTextValue:_totalDes];
        });
        return cell;
    }
    else {
        LeaderYijianCell *cell=[LeaderYijianCell cellWithTableView:tableView];
        cell.isEdit=self.isEdit;
        NSMutableDictionary *dict=self.dataArray[indexPath.section-1];
        NSMutableArray *arr=[dict objectForKey:@"array"];
        NSMutableDictionary *cellDataDic=arr[indexPath.row];
        /**
         *添加操作
         **/
        if(self.isEdit){
            //根据状态判断是否合格
            NSString *state=cellDataDic[@"state"];
            [cell setCellType:@"add" State:state isIcon:NO];
            //状态为不合格
            if([state isEqualToString:@"0"]){
                allQualified=NO;
            }
            //设置标题
            NSString *title=cellDataDic[@"inspectItemInfo"];
            
            cell.titleField.text=title;
            //执行编辑操作
            cell.textValueChangedBlock=^(NSString *value){
                //重新设置标题
                [cellDataDic setValue:value forKey:@"inspectItemInfo"];
            };
            //设置姓名
            cell.name.text=cellDataDic[@"name"];
            //详情信息
            cell.detailBlick=^{
                //不合格
                if([state isEqualToString:@"0"]){
                    NSString *userItemState=[LSUtility getUserItemState:cellDataDic[@"ids"]];
                    NSLog(@"状态:%@",userItemState);
                    //有不合格就变为NO
                    allQualified=NO;
                    //查看该记录是否存在待审核
                    if([userItemState isEqualToString:@"2"]){
                        LeaderAddInspController *leaderVC=[[LeaderAddInspController alloc]init];
                        leaderVC.isEdit=NO;
                        leaderVC.prosessId=cellDataDic[@"ids"];
                        leaderVC.ipqc=cellDataDic[@"types"];
                        leaderVC.inspectUserId=cellDataDic[@"inspectUserId"];
                        [self.navigationController pushViewController:leaderVC animated:YES];
                    }else{
                        LeaderAddInspController *leaderVC=[[LeaderAddInspController alloc]init];
                        leaderVC.isEdit=NO;
                        leaderVC.prosessId=cellDataDic[@"ids"];
                        leaderVC.ipqc=cellDataDic[@"types"];
                        leaderVC.inspectUserId=cellDataDic[@"inspectUserId"];
                        [self.navigationController pushViewController:leaderVC animated:YES];
                    }
                //合格
                }else{
                    //跳转到记录页面
                    LeaderAddInspController *leaderVC=[[LeaderAddInspController alloc]init];
                    leaderVC.isEdit=NO;
                    leaderVC.prosessId=cellDataDic[@"ids"];
                    leaderVC.ipqc=cellDataDic[@"types"];
                    leaderVC.inspectUserId=cellDataDic[@"inspectUserId"];
                    [self.navigationController pushViewController:leaderVC animated:YES];
                }
            };
//            //执行删除操作
            cell.dltBlock=^{
//                NSLog(@"当前删除行：%li",indexPath.row);
                [arr removeObjectAtIndex:indexPath.row];
                if(arr.count==0){
                    [self.dataArray removeObject:dict];
//                    NSLog(@"%li",indexPath.section);
                    [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationRight];
                }else{
                    @try {
                        
                        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationFade)];
                        
                    } @catch (NSException *exception) {
                        NSLog(@"error:%@",exception);
                        
                    } @finally {
                        
                    }
                }
                [self.tableView reloadData];
            };
        }else{
            /**
             * 查看操作
             **/
            
            //设置标题
            NSString *totalTitle=cellDataDic[@"inspectItemInfo"];
            if([totalTitle isEqualToString:@""]){
                totalTitle=@"无";
            }
            cell.titleField.text=totalTitle;
            //根据状态判断是否合格
            NSString *state=cellDataDic[@"inspectResult"];
            
            //根据id 查询userItem状态
            NSString *userItemState=[LSUtility getUserItemState:cellDataDic[@"recordId"]];
            //如果为不合格 查询是否进行整改
            if([state isEqualToString:@"0"]){
                //查询用户巡检项表 很关键
                NSString *states=[LSUtility queryUserItemStateById:cellDataDic[@"userItemId"]];
                //存在待审阅
                if([states isEqualToString:@"4"]){
                    [cell setCellType:@"zheng" State:state isIcon:YES];
                }else{
                    //判断是否结束
                    NSString *counts=[LSUtility getInspectStop:cellDataDic[@"recordId"]];
                    if([counts isEqualToString:@"1"]){
                        state=@"1";
                        [cell setCellType:@"query" State:state isIcon:YES];
                    }else{
                        [cell setCellType:@"query" State:state isIcon:NO];
                        int i=[LSUtility getInspectItemCountByUserItemID:cellDataDic[@"userItemId"] withState:@"3"];
                        //审阅不合格 继续整改
                        if(i>1&&[userItemState isEqualToString:@"3"]){
                            [cell setCellType:@"query" State:@"0" isIcon:YES];
                        }else{
                            [cell setCellType:@"query" State:@"0" isIcon:NO];
                        }
                    }
                }
                
                [cellDataDic setValue:@"inspectState" forKey:@"inspectState"];
                
            }else{
                //一次性合格
                [cell setCellType:@"firstQualified" State:state isIcon:YES];
                [cellDataDic setValue:@"flag" forKey:@"inspectState"];

            }
            //设置姓名
            NSString *names=cellDataDic[@"name"];
            if([names isEqualToString:@""]){
            names=@"未知";
            }
            cell.name.text=names;
            //详情信息
            cell.detailBlick=^{
                if([state isEqualToString:@"0"]){
                    //判断是否为待整改
                    if([LSUtility getProcessRecordState4:cellDataDic[@"recordId"]]){
                        LeaderAuditController *leader=[[LeaderAuditController alloc]init];
                        leader.recordId=cellDataDic[@"recordId"];
                        leader.ipqc=cellDataDic[@"types"];
                        //跳转到审阅查看页面
                        if(![[LSUtility getInspectStop:cellDataDic[@"recordId"]] isEqualToString:@"0"]){
                            //已经结束 查看页面
                            leader.isEdit=NO;
                        }else{
                            //最近一条是本人审阅 查看页面
                            if([LSUtility isLastInspectProcessRecord:cellDataDic[@"userItemId"]]){
                                leader.isEdit=NO;
                            }else{
                                leader.isEdit=YES;
                            }
                        }
                        //跳转到审阅界面
                        [self.navigationController pushViewController:leader animated:YES];
                        
                    }else{
                        //跳转到记录页面
                        LeaderAddInspController *leaderVC=[[LeaderAddInspController alloc]init];
                        leaderVC.isEdit=NO;
                        leaderVC.taskId=self.processId;
                        leaderVC.prosessId=cellDataDic[@"recordId"];
                        leaderVC.ipqc=cellDataDic[@"types"];
                        [self.navigationController pushViewController:leaderVC animated:YES];
                    }
                }else{
                    //不合格 还需要在整改
                    if([cellDataDic[@"inspectState"] isEqualToString:@"inspectState"]){
                        LeaderAuditController *leader=[[LeaderAuditController alloc]init];
                        leader.recordId=cellDataDic[@"recordId"];
                        leader.ipqc=cellDataDic[@"types"];
                        leader.isEdit=NO;
                        [self.navigationController pushViewController:leader animated:YES];
                        
                    }else{
                        //添加到记录页面
                        LeaderAddInspController *leaderVC=[[LeaderAddInspController alloc]init];
                        leaderVC.isEdit=NO;
                        leaderVC.prosessId=cellDataDic[@"recordId"];
                        leaderVC.ipqc=cellDataDic[@"types"];
                        leaderVC.taskId=self.processId;
                        [self.navigationController pushViewController:leaderVC animated:YES];
                    }
                }
            };
        }
    return cell;
    }
}

//- (void)textViewCell:(LeaderYijianCell *)cell didChangeText:(NSString *)text
//{
//    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
//    NSMutableArray *data = [self.dataArray mutableCopy];
//    data[indexPath.row] = text;
//    self.dataArray = [data copy];
//}

#pragma mark scrollview
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == self.tableView) {
        [self.view endEditing:YES];
    }
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end


